import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {},
    status:'',
    token: localStorage.getItem('token') || ''
  },
  getters: {
    user(state) {
      return state.user
    }
  },
  mutations: {
    //登录
    login(state, res) {
      state.token = res.token
      localStorage.setItem('token', state.token)
      axios.defaults.headers.common.Authorization = state.token
    },
    //登出
    logout(state) {
      state.token = ''
      localStorage.removeItem('token')
      delete axios.defaults.headers.common.Authorization
    },
    //获取当前用户信息
    current(state, res) {
      state.user=res.data
      // console.log(res.data);
    },
  },
  actions: {
    //登录
    login({commit}, payload) {
      return new Promise((resolve) => {
        axios.post('http://127.0.0.1:8080/api/user/login', payload).then(res => {
          commit('login', res.data)
          resolve(res.data)
        })
      })
    },
    //获取当前用户信息
    current({commit}, payload) {
      return new Promise((resolve) => {
        axios.get('http://127.0.0.1:8080/userinfo/current').then((res) => {
          commit('current', res.data)
          resolve(res.data)
        })
      })
    }
  },
  modules: {}
})